package com.rh.manage.config;

import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.CharsetUtil;
import com.alibaba.fastjson.JSONObject;
import com.rh.manage.exception.ApplicationException;
import com.rh.manage.exception.ErrorCodeEnum;
import com.rh.manage.model.UserConfig;
import lombok.Getter;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.FileInputStream;
import java.io.FileOutputStream;

/**
 * 读取用户配置文件
 */
@Getter
@Component
public class ReadUserConfig {

    public UserConfig userConfig;

    @PostConstruct
    public void init() throws Exception {
        String json = IoUtil.read(new FileInputStream("config.json"), CharsetUtil.UTF_8);
        if (StringUtils.isBlank(json)) {
            return;
        }
        userConfig = JSONObject.parseObject(json, UserConfig.class);
    }

    /**
     * 将配置写入到文件
     */
    public void writeToFile() {
        if (userConfig == null) {
            return;
        }
        String json = JSONObject.toJSONString(userConfig, true);
        try {
            FileOutputStream out = new FileOutputStream("config.json");
            IoUtil.write(out, true, json.getBytes());
        } catch (Exception e) {
            throw new ApplicationException(ErrorCodeEnum.FAILED_TO_WRITE_CONFIGURATION_FILE, e);
        }
    }

    public void setMindAppCmd(String openMindAppCmd) {
        if (StringUtils.isBlank(openMindAppCmd)) {
            return;
        }
        if (userConfig == null) {
            userConfig = new UserConfig();
        }
        userConfig.setMindAppCmd(openMindAppCmd);
    }

    public void setGitProjectPath(String gitProjectPath) {
        if (StringUtils.isBlank(gitProjectPath)) {
            return;
        }
        if (userConfig == null) {
            userConfig = new UserConfig();
        }
        userConfig.setGitProjectPath(gitProjectPath);
    }
}
